package ebcs.scan.controller.sys;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import ebcs.app.auto.transmodel.sys.FileUploadReqModel;
import ebcs.app.auto.transmodel.sys.ParameterReqModel;
import ebcs.app.auto.transmodel.sys.UseLoginReqModel;
import ebcs.database.bean.sys.FileStorage;
import ebcs.database.bean.sys.PaAgency;
import ebcs.database.bean.sys.PaParameter;
import ebcs.database.bean.sys.PaRole;
import ebcs.database.bean.sys.PaUser;
import ebcs.database.bean.sys.PaUserRoleFunc;
import ebcs.database.bean.sys.SysCtiy;
import ebcs.database.service.sys.IAgencyManagerService;
import ebcs.database.service.sys.IParameterService;
import ebcs.database.service.sys.IUserFuncManagerService;
import ebcs.database.service.sys.IUserManagerService;
import ebcs.scan.bean.sys.FileStorageBean;
import ebcs.scan.bean.sys.SysUserInfor;
import ebcs.scan.common.consts.KPlatSysConsts;
import ebcs.scan.common.utils.Pdf2Img;
import ebcs.scan.service.sys.fileStorage.FileStorageService;
import jplat.core.session.JSession;
import jplat.core.session.redis.JRedisSession;
import jplat.core.trans.JAppBaseService;
import jplat.core.trans.JAppContext;
import jplat.core.trans.JAppContextFactory;
import jplat.error.exception.JSystemException;
import jplat.error.exception.JTransException;
import jplat.tools.coder.Base64Coder;
import jplat.tools.coder.MD5Utils;
import jplat.tools.config.JAppConfig;
import jplat.tools.config.JBusConfig;
 

/***
 *  系统管理
 * @author chenzhuo
 * @comment 
 */
@Controller
public class SystemManagerCtrl extends JAppBaseService
{
	private Logger logger = Logger.getLogger(SystemManagerCtrl.class);
	protected JAppContextFactory serviceFactory = new JAppContextFactory();
	//数据库库服务.
	@Autowired 
	public IUserManagerService userService ; 
	@Autowired
	public IAgencyManagerService agencyService;
	@Autowired
	public IUserFuncManagerService userfuncService;
	@Autowired
	public FileStorageService fileStorageService;
	@Autowired
	public IParameterService paraService;
	
	@RequestMapping("/ns0/doAuthentication.do")
	@ResponseBody
	public Map<String,Object> doAuthentication(  HttpServletRequest request, HttpServletResponse response )throws JTransException, JSystemException
	{
  		Map<String,Object> retMap = new HashMap<String,Object>();
		
		JSession  session = new JRedisSession();
		Cookie sessCookie= new Cookie("ttkn2",session.getSessionID());
		sessCookie.setPath("/");
		response.addCookie(sessCookie);
		
 		return retMap;
	}
	/**
	 * 用户登陆验证
	 */
 	@RequestMapping("/ns0/sys/login.do")
	public void login( HttpServletRequest request,HttpServletResponse response ) throws JTransException, JSystemException{
		JAppContext context = serviceFactory.buildAppContextNoUser(request,response);		//buildAppContextWithUser 自带客户信息.
		UseLoginReqModel userReq = context.obtainReqModel(UseLoginReqModel.class);
		//根据用户No查询用户信息
		List<PaUser> userList = this.userService.seachUserInforByUserNo(userReq.getUserNo());
 	 	if(userList.size()==0){
 	 		throw new JTransException(KPlatSysConsts.SYS_ERROR_USER,"用户名或密码错误");//特别处理，都设置为【用户名或密码错误】，防止客户重复试用
 	 	}
 	 	
 	 	PaUser userBean = userList.get(0);
 	 	String parseMD5Passwd = "";
		try {
			parseMD5Passwd = MD5Utils.md5(userReq.getPassword());
		} catch (Exception e) {
			logger.error("用户密码转换错误:" + e.getMessage());
			throw new JSystemException(KPlatSysConsts.SYS_ERROR_USER, "用户密码转换错误");
		}
		
 	 	if(!parseMD5Passwd.equals(userBean.getPassword())) { //密码存储格式后续商量改造（存MD5还是另外有加密算法）
 	 		throw new JTransException(KPlatSysConsts.SYS_ERROR_USER,"用户名或密码错误");
 	 	}
 	 	 
 	 	//创建会话
 	 	saveSessionInfor(context,userBean);
 	 	
		Map rsModel = new HashMap();
  		context.buildAppResponse(null);
	}
	//保存会话
	private void saveSessionInfor(JAppContext context,PaUser userBean) throws JSystemException  {
		SysUserInfor userSession = new SysUserInfor();
 	 	userSession.setUserId(userBean.getUserId());
 	 	userSession.setUserNo(userBean.getUserNo());
 	 	userSession.setUserName(userBean.getUserName());
 	 	userSession.setPhone(userBean.getPhone());
 	 	userSession.setEmail(userBean.getEmail());
  	 	//会话中新增机构信息
 	 	PaAgency agency = this.agencyService.searchAgencyInforByAgenId(userBean.getAgenId());
 	 	userSession.setAgency(agency);
 	 	//会话中新增角色列表
 	 	List<PaRole> roleList = this.userfuncService.selectRoleByUserId(userBean.getUserId());
 	 	userSession.setRoleList(roleList);
 	 	
 	 	List<PaUserRoleFunc> uf = this.userfuncService.selectUserFuncListByUserId(userBean.getUserId());
 	 	userSession.setFuncList(uf);
 	 	
 	 	JSession  session = context.createSession(true);
 	 	session.setUserInfo(userSession);
 	 	
 	 	if(JAppConfig.IS_TEST){
 	 		HttpServletResponse response = context.getResponse() ;
 	 		Cookie sessCookie= new Cookie("ttkn2",session.getSessionID());
 			sessCookie.setPath("/");
 			response.addCookie(sessCookie);
 	 	}
 	 	
	}
	//拉去客户信息
	@RequestMapping("/sys/user/pullUserInforV0.do")
	public void pullUserInforV0( HttpServletRequest request,HttpServletResponse response ) throws JTransException, JSystemException{
		JAppContext context = serviceFactory.buildAppContextWithUser(request, response);
		SysUserInfor userInfor = context.getUserInfo();
		//获取菜单信息
		PaUserRoleFunc userfuncList= userfuncService.selectUserFuncByUserId(userInfor.getUserId());
		
		Map rsModel = new HashMap();
		rsModel.put("userfuncList", userfuncList);
		rsModel.put("userNo", userInfor.getUserNo());
		rsModel.put("userName", userInfor.getUserName());
		rsModel.put("phone", userInfor.getPhone());
		rsModel.put("email", userInfor.getEmail());
		rsModel.put("belongAgency", userInfor.getAgency());
  		context.buildAppResponse(rsModel);
	}
	
	
	//获取参数信息
	@RequestMapping("/sys/param/getParameter.do")
	public void getParameter( HttpServletRequest request,HttpServletResponse response ) throws JTransException, JSystemException{
		JAppContext context = serviceFactory.buildAppContextWithUser(request, response);
		ParameterReqModel req = context.obtainReqModel(ParameterReqModel.class); 
		//获取菜单信息
		List<PaParameter> rsList = paraService.selectParameterByPapaid(req.getPapaId());
		Map rsModel = new HashMap();
		rsModel.put("paraList", rsList);
		context.buildAppResponse(rsModel);
	}
	//获取参数信息
		@RequestMapping("/sys/param/getCity.do")
		public void getCity( HttpServletRequest request,HttpServletResponse response ) throws JTransException, JSystemException{
			JAppContext context = serviceFactory.buildAppContextWithUser(request, response);
			ParameterReqModel req = context.obtainReqModel(ParameterReqModel.class); 
			//获取菜单信息
			List<SysCtiy> rsList = paraService.selectSysCtiyList(req.getPapaId());
			Map rsModel = new HashMap();
			rsModel.put("cityList", rsList);
	  		context.buildAppResponse(rsModel);
		}
		

		/**
		 * 写文件服务
		 * 
		 * @param request
		 * @param response
		 * @throws JTransException
		 * @throws JSystemException
		 */
		@RequestMapping("/sys/file/fileUpload.do")
		public void dofileUpload(HttpServletRequest request, HttpServletResponse response)
				throws JTransException, JSystemException {
			JAppContext context = serviceFactory.buildAppContextWithUser(request, response); // buildAppContextWithUser
																								// 自带客户信息.
			FileUploadReqModel fileReq = context.obtainReqModel(FileUploadReqModel.class);
			SysUserInfor sysuser = context.getUserInfo();
			String fileBase64Str = fileReq.getFileBase64Data();
			String fileBase64 = fileBase64Str.substring(fileBase64Str.indexOf("base64") + 7, fileBase64Str.length());

			
			byte[] uploadByte = Base64Coder.fromBase64String(fileBase64);
			FileStorageBean fileStorage = new FileStorageBean();
			fileStorage.setStorageName(fileReq.getFileName());
			fileStorage.setUserNo(sysuser.getUserNo());
			fileStorage.setFileData(uploadByte);
			
			FileStorage fileSt = this.fileStorageService.writeToFileStorageReturnObject(fileStorage);//1.存储到文件服务器中
			List imagUrlList = new ArrayList();
			if (fileBase64Str.indexOf("application/pdf") != -1) {
				List<String> imageList = new ArrayList();
				String filePkg = JBusConfig.FILE_SERVICE_PATH+fileSt.getStoragePath();
				String filePath = filePkg +"/";
	 			String inDir = filePath;
				String outDir = inDir;
				try {
					imageList = Pdf2Img.doParse(uploadByte,fileSt.getStorageId(), inDir, outDir, true);
				} catch (IOException e) {
					e.printStackTrace();
				}
				for(String imgUrl:imageList) {
					imagUrlList.add(JBusConfig.STATIC_SERVICE_URL + String.format(fileSt.getStoragePath()+"/%s", new Object[] { imgUrl }));
				}
 				//更新PDF页数到文件系统数据中
				int i = this.fileStorageService.updatePdfLength(fileSt.getStorageId(), imageList.size());
				if(i==0) {
					logger.error("pdf parse  error,storageId="+fileSt.getStorageId());
					throw new JTransException(KPlatSysConsts.SYS_ERROR_FILESTORAGE,"PDF文件系统上传错误!");
				}
			}
			if (fileBase64Str.indexOf("data:image") != -1) {
				imagUrlList.add(JBusConfig.STATIC_SERVICE_URL + String.format(fileSt.getStoragePath()+"/%s", new Object[] { fileSt.getStorageId() }));
			}
			Map rsModel = new HashMap();
			rsModel.put("storageId", fileSt.getStorageId());
			rsModel.put("downloadUrl", String.format(JBusConfig.APP_URL+"/ns0/sys/file/%s/fileDownload.do", new Object[] {fileSt.getStorageId()}));
			rsModel.put("imagUrlList", imagUrlList);
			context.buildAppResponse(rsModel);
		}
		
		
		
		
		/**
		 * 写文件服务
		 * @param request
		 * @param response
		 * @throws JTransException
		 * @throws JSystemException
		 */
		@RequestMapping("/ns0/sys/file/{storageId}/fileDownload.do")
		public ResponseEntity<byte[]> dofileDownload( HttpServletRequest request,HttpServletResponse response ,@PathVariable String storageId ) throws JTransException, JSystemException{
		      FileStorageBean  fileStorageBean = this.fileStorageService.loadFileStoragEntity(storageId);
		      InputStream in=new ByteArrayInputStream(fileStorageBean.getFileData());//将该文件加入到输入流之中
		      byte[] body=null;
		      try {
				body=new byte[in.available()];
				 in.read(body);
			      String fileName = fileStorageBean.getStorageName();
			      fileName=new String(fileName.getBytes("gbk"),"iso8859-1");//防止中文乱码
			        HttpHeaders headers=new HttpHeaders();//设置响应头
			        headers.add("Content-Disposition", "attachment;filename="+fileName);
			        HttpStatus statusCode = HttpStatus.OK;//设置响应吗
			        ResponseEntity<byte[]> res=new ResponseEntity<byte[]>(body, headers, statusCode);
			        return res;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		      return null;
		}
		
		

		/**
		 * 
		 * @Title: searchLatelyFileStorageList   
		 * @Description: TODO(根据实体信息查询最近存储文件信息)   
		 * @param: @param request
		 * @param: @param response
		 * @param: @throws JTransException
		 * @param: @throws JSystemException      
		 * @return: void      
		 * @throws
		 */
		@RequestMapping("/sys/file/searchLatelyFileStorageList.do")
		public void searchLatelyFileStorageList(HttpServletRequest request, HttpServletResponse response)
				throws JTransException, JSystemException {
			JAppContext context = serviceFactory.buildAppContextWithUser(request, response); // buildAppContextWithUser
			FileStorageBean fileReq = context.obtainReqModel(FileStorageBean.class); 
			FileStorageBean rsFileInfo = this.fileStorageService.searchLatelyFileStorageList(fileReq.getEntityNo(), fileReq.getEntityName(),fileReq.getEntityType());
			context.buildAppResponse(rsFileInfo);
		}
		/**
		 * 
		 * @Title: updateFileStorage   
		 * @Description: TODO(更新文件信息)   
		 * @param: @param request
		 * @param: @param response
		 * @param: @throws JTransException
		 * @param: @throws JSystemException      
		 * @return: void      
		 * @throws
		 */
		@RequestMapping("/sys/file/updateFileStorage.do")
		public void updateFileStorage(HttpServletRequest request, HttpServletResponse response)
				throws JTransException, JSystemException {
			JAppContext context = serviceFactory.buildAppContextWithUser(request, response); // buildAppContextWithUser
			FileStorageBean fileReq = context.obtainReqModel(FileStorageBean.class); 
			int i = this.fileStorageService.updateFileStorage(fileReq.getStorageId(),fileReq.getEntityNo(), fileReq.getEntityName(),fileReq.getEntityType());
			if(i==0) {
				throw new JTransException(KPlatSysConsts.SYS_ERROR_USER,"文件上传错误");
			}
			Map rsModel = new HashMap();
			context.buildAppResponse(rsModel);
		}
		
		
		/**
		 * 
		 * @Title: searchLatelyFileStorageList   
		 * @Description: TODO(根据文件ID查询文件信息)   
		 * @param: @param request
		 * @param: @param response
		 * @param: @throws JTransException
		 * @param: @throws JSystemException      
		 * @return: void      
		 * @throws
		 */
		@RequestMapping("/sys/file/searchFileStorageByStoageId.do")
		public void searchFileStorageByStoageId(HttpServletRequest request, HttpServletResponse response)
				throws JTransException, JSystemException {
			JAppContext context = serviceFactory.buildAppContextWithUser(request, response); // buildAppContextWithUser
			FileStorageBean fileReq = context.obtainReqModel(FileStorageBean.class); 
			FileStorageBean rsFileInfo = this.fileStorageService.searchFileStorageByStorageId(fileReq.getStorageId());
			context.buildAppResponse(rsFileInfo);
		}
	
		
		/**
		 * 用户退出登陆
		 */
	 	@RequestMapping("/sys/logout.do")
		public void logout(HttpServletRequest request, HttpServletResponse response)
				throws JTransException, JSystemException {
			JAppContext context = serviceFactory.buildAppContextWithUser(request, response); // buildAppContextWithUser
			if(context.clearSession()) {
				context.buildAppResponse(null);
			}else {
				throw new JTransException(KPlatSysConsts.SYS_ERROR_USER,"退出失败，请稍后再试试");
			}
			
		}
	
}
